<template>
  <!-- 空容器用于挂载脚本 -->
  <div ref="difyContainer"></div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch,Ref } from 'vue-property-decorator';

@Component
export default class DifyChat extends Vue {
  @Prop({ type: String, required: true }) readonly token!: string;
  @Prop({ type: String, required: true }) readonly baseUrl!: string;
  @Prop({ type: String, default: '' }) readonly userId!: string;
  @Prop({ type: String, default: '' }) readonly conversationId!: string;
  @Ref('difyContainer') private difyContainer;
  
  private scriptLoaded = false;
  private existingScript: HTMLScriptElement | null = null;

  mounted() {
    console.log('start')
    this.initDify();
  }

  
  beforeDestroy() {
    this.cleanup();
      console.log('end')
  }

  @Watch('userId')
  @Watch('conversationId')
  onParamsChanged() {
    this.updateConfig();
  }

  private initDify() {
    this.setGlobalConfig();
    
    if (!this.scriptLoaded) {
      this.loadScript();
    } else {
      this.updateConfig();
    }
  }

  private setGlobalConfig() {
    // 设置全局配置（响应式更新）
    window.difyChatbotConfig = {
      token: this.token,
      baseUrl: this.baseUrl,
      systemVariables: {
        ...(this.userId && { user_id: this.userId }),
        ...(this.conversationId && { conversation_id: this.conversationId })
      }
    };
  }

  private loadScript() {
    // 清除旧脚本
    this.cleanup();

    // 创建新脚本
    // 清除旧脚本
    this.cleanup();

    // 创建新脚本
    // 创建新脚本
    const script = document.createElement('script');
    script.src = `${this.baseUrl}/embed.min.js`;
    script.id = `dify-script-${this.token}`;
    script.defer = true;
    script.onload = () => {
      // 脚本加载完成后，将脚本加载标志设置为true，并将当前脚本保存为已存在的脚本
      this.scriptLoaded = true;
      this.existingScript = script;
    };

    // 将新脚本添加到容器中
    this.difyContainer.appendChild(script);
  }

  private updateConfig() {
    if (window.difyChatbotConfig) {
      // 热更新配置
      window.difyChatbotConfig.systemVariables = {
        ...window.difyChatbotConfig.systemVariables,
        ...(this.userId && { user_id: this.userId }),
        ...(this.conversationId && { conversation_id: this.conversationId })
      };
      
      // 调用Dify内部更新方法（如果可用）
    //   if (window.difyChatbotConfig) {
    //     this.updateConfig(window.difyChatbotConfig);
    //   }
    }
  }

  private cleanup() {
    // 移除旧脚本
    if (this.existingScript) {
      this.existingScript.remove();
      this.existingScript = null;
    }
    this.scriptLoaded = false;
    
    // 清理Dify DOM元素
    const elements = [
      document.getElementById('dify-chatbot-bubble-button'),
      document.getElementById('dify-chatbot-bubble-window')
    ];
    
    elements.forEach(el => {
      if (el) el.remove();
    });
  }
}
</script>

<style scoped>
/* 空样式 - 实际样式在全局 */
#dify-chatbot-bubble-window{
    position: relative;
    right: 0px;
    bottom: 0px;
}
</style>